package com.leyou.upload.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.test.enums.ExceptionEnum;
import com.leyou.test.exceptions.LyException;
import com.leyou.upload.config.OSSConfig;
import com.leyou.upload.config.OSSProperties;
import com.leyou.upload.service.IUpLoadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
public class UpLoadServiceImpl implements IUpLoadService {
    @Autowired
    private OSS ossClient;
    @Autowired
    private OSSProperties ossProperties;

    //上传图片支持的格式
    private static final List<String> suffixes = Arrays.asList("image/png", "image/jpeg", "image/bmp");

    /**
     * 上传图片
     * @param file
     * @return
     */
    @Override
    public String upLoad(MultipartFile file) {
        //判断文件格式是否为图片格式
        String contentType = file.getContentType();
        if (!suffixes.contains(contentType)) {
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }

        //判断文件内容是否为图片
        BufferedImage bufferedImage = null;
        try {
            bufferedImage = ImageIO.read(file.getInputStream());
        } catch (IOException e) {
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }
        if (null == bufferedImage) {
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }

        //文件要保存的位置目录
        File dir = new File("D:\\nginx-1.12.2\\nginx-1.12.2\\html\\");
        //如果目录不存在,则创建目录
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //进行文件的保存
        try {
            file.transferTo(new File(dir, file.getOriginalFilename()));
            System.out.println(file.getOriginalFilename());
            return "http://image.leyou.com/"+file.getOriginalFilename();
        } catch (IOException e) {
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }
    }

    /**
     * 上传图片到阿里云
     * @return
     */
    @Override
    public Map<String, Object> getAliSignature() {
        try {
            long expireTime = ossProperties.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, ossProperties.getMaxFileSize());
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, ossProperties.getDir());

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            Map<String, Object> respMap = new LinkedHashMap<String, Object>();
            respMap.put("accessId", ossProperties.getAccessKeyId());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", ossProperties.getDir());
            respMap.put("host", ossProperties.getHost());
            respMap.put("expire", expireEndTime);
            return respMap;
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
    }
}
